package controllers

import (
	"doc-man/models"
	beego "github.com/beego/beego/v2/server/web"
)

type Doctor struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (d *Doctor) Add() {

	Name := d.GetString("name")
	Tel := d.GetString("tel")
	Yy := d.GetString("yy")
	Ks := d.GetString("ks")
	Zc := d.GetString("zc")
	Time := d.GetString("time")
	Zt := d.GetString("zt")
	Fw := d.GetString("fw")
	Fs := d.GetString("fs")
	doctor := models.Doctor{
		Name: Name,
		Tel:  Tel,
		Yy:   Yy,
		Ks:   Ks,
		Zc:   Zc,
		Time: Time,
		Zt:   Zt,
		Fw:   Fw,
		Fs:   Fs,
	}
	if Name == "" || Tel == "" || Yy == "" || Ks == "" || Zc == "" || Time == "" || Zt == "" || Fw == "" || Fs == "" {
		d.Data["json"] = Res{
			Code: 0,
			Msg:  "数据不能为空",
		}
		d.ServeJSON()
		return
	}
	err := models.DB.Create(&doctor).Error

	if err != nil {
		d.Data["json"] = Res{
			Code: 0,
			Msg:  "添加成功",
		}
		d.ServeJSON()
		return
	} else {
		d.Data["json"] = Res{
			Code: 200,
			Msg:  "添加失败",
		}
		d.ServeJSON()
	}
}
func (d *Doctor) List() {

	page, _ := d.GetInt("page", 1)
	size, _ := d.GetInt("size", 3)
	offset := (page - 1) * size
	query := models.DB.Model(&models.Doctor{})
	var count int64
	query.Count(&count)
	var doctor []models.Doctor
	name := d.GetString("name")
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	err := query.Offset(offset).Limit(size).Find(&doctor).Error
	if err != nil {
		d.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
		}
		d.ServeJSON()
		return
	} else {
		d.Data["json"] = Res{
			Code: 200,
		}
		d.ServeJSON()
	}
}
func (d *Doctor) Update() {

	id, _ := d.GetInt("id")
	Name := d.GetString("name")
	Tel := d.GetString("tel")
	Yy := d.GetString("yy")
	Ks := d.GetString("ks")
	Zc := d.GetString("zc")
	Time := d.GetString("time")
	Zt := d.GetString("zt")
	Fw := d.GetString("fw")
	Fs := d.GetString("fs")
	doctor := models.Doctor{
		Name: Name,
		Tel:  Tel,
		Yy:   Yy,
		Ks:   Ks,
		Zc:   Zc,
		Time: Time,
		Zt:   Zt,
		Fw:   Fw,
		Fs:   Fs,
	}
	err := models.DB.Where("id=?", id).Updates(&doctor).Error
	if err != nil {
		d.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
		}
		d.ServeJSON()
		return
	} else {
		d.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
		}
		d.ServeJSON()
	}
}
func (d *Doctor) Del() {

	id, _ := d.GetInt("id")
	err := models.DB.Delete(&models.Doctor{}, id).Error
	if err != nil {
		d.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
		}
		d.ServeJSON()
		return
	} else {
		d.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
		}
		d.ServeJSON()
	}
}
